package com.example.camera;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private ImageButton button;
    private GridView gridView;
    private ArrayList<Bitmap> photoList;
    private ArrayList<PhotoInfo> photoInfoList;
    private PhotoDBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        button = findViewById(R.id.button);
        gridView = findViewById(R.id.gridView);
        photoList = new ArrayList<>();
        photoInfoList = new ArrayList<>();
        dbHelper = new PhotoDBHelper(this);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
            }
        });



        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showPhotoDetail(position);
            }
        });


        loadLastPhotos();
    }


    private void takePhoto() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if (intent.resolveActivity(getPackageManager()) != null) {

            startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");

            String time = String.valueOf(System.currentTimeMillis() / 1000);

            Location location = getCurrentLocation();

            if (location != null) {

                double latitude = location.getLatitude();
                double longitude = location.getLongitude();

                PhotoInfo photoInfo = new PhotoInfo(imageBitmap, time, latitude, longitude);

                dbHelper.insertPhoto(photoInfo);

                photoList.add(imageBitmap);
                if (photoList.size() > 10) {
                    photoList.remove(0);
                }
                gridView.setAdapter(new ImageAdapter(this, photoList));

                photoInfoList.add(photoInfo);
                if (photoInfoList.size() > 10) {
                    photoInfoList.remove(0);
                }
            } else {

                Toast.makeText(this, "Location is not available.", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private Location getCurrentLocation() {

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            return location;
        } else {

            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);

            return null;
        }
    }


    private void loadLastPhotos() {

        ArrayList<PhotoInfo> photos = dbHelper.queryAllPhotos();
        int size = photos.size();

        if (size > 0) {

            for (int i = Math.max(0, size - 10); i < size; i++) {

                PhotoInfo photo = photos.get(i);

                photoList.add(photo.getImage());
                photoInfoList.add(photo);
            }

            gridView.setAdapter(new ImageAdapter(this, photoList));
        } else {

            Toast.makeText(this, "There are no photos in the database.", Toast.LENGTH_SHORT).show();
        }
    }


    private void showPhotoDetail(int position) {

        Intent intent = new Intent(this, PhotoDetailActivity.class);

        intent.putExtra("photo_info", photoInfoList.get(position));

        startActivity(intent);
    }
}